class AdminController < ApplicationController

before_filter :login_required
  
  def index
    #redirect_to :action=>"album_list"
  end

  def image_tag_edit
    @id=params[:id].split(/photo_\s*/)
    @photo=Photo.find("#{@id}")
  end

  def update_tags
    photo=Photo.find(params[:photo_id])
    st=params[:tags]
    while st do
      tagname,st=st.split(/\s*,\s*/)
      if tagname
      photo.add_tag(tagname)
      end
    end
    @photo=photo
    render :update do |page|
      page.replace_html "tags_to_delete", :partial=>"existing_tags"
      page["tags"].value=""
      page.replace "tags_update", :partial=>"tags"
    end
  end

  def autocomplete_add_new_tags
    @tags=Tag.find :all, :order=>"title", :conditions => [ 'LOWER(title) LIKE ?',
    '%' + params[:tags].downcase + '%' ]
    render :layout=>false
  end

  def remove_tag
    photo=Photo.find(params[:photo_id])
    photo.delete_tag(params[:tag])
    @photo=photo
    render :update do |page|
      page.replace_html "tags_to_delete", :partial=>"existing_tags"
    end
  end

   def tag_settings
     if request.post? 
       #some nessesary code#
       flash[:notice]="balbalbal" 
       #                   #
       if params[:tags]!=''
         st=params[:tags]
           tagnames=st.split(/\s*,\s*/)
             for tagname in tagnames
                 @bool = 0
                 tagname = tagname.strip
                 tags=Tag.find :all
                   tags.each do |t|
                      if t.title==tagname
                        @bool = 1
                      end
                   end
                if @bool==0
                  @tag = Tag.new
                  @tag.title = tagname
                  @tag.save
                    if flash[:notice]=="balbalbal" 
                       flash[:notice] = "Tags was successfully added"
                    end
                else
                  if flash[:notice].include? "These tags have been already added: "
                    flash[:notice]=flash[:notice]+'['+tagname+']'+' '
                  else
                    flash[:notice]="These tags have been already added: "+'['+tagname+']'+' '
                  end
                end
             end
       else
         flash[:notice] = "Please, type your tag"
       end
    end
   end
   
   def tag_destroy
     tag = Tag.find_by_title(params[:tag])
     tag.destroy
     redirect_to :action => 'tag_settings'
   end
   
   def destroy
    @photo = Photo.find(params[:id])
    @album = Album.find(params[:album])
    title = @album.title
    if @album.cover!=nil
      if @album.cover == Integer(params[:num])
        @album.cover = nil
      else
         if @album.cover > Integer(params[:num])
            @album.cover = @album.cover-1
         end
      end
    end
    @album.save
    @photo.rm(title)
    @photo.destroy
   
    redirect_to :action => 'album_page',:id=>params[:album]
  end
  
   def change_album_representer
    @album = Album.find(params[:id])
    @album.cover = Integer(params[:num]) 
    @album.save
    redirect_to :action => 'album_list',:id=>params[:id]
    
  end


  def album_page
    @i = 0
    @album = Album.find params[:id]
    @photos = @album.photos
    render :action=>'album_page'
  end

  def edit_photo
    @photo = Photo.find(params[:id])
    @album=@photo.albums[0]
  end

  def album_list
    @i = 0
    @photos = Array.new
    @albums = Album.find :all
    for album in @albums
     if album.cover!=nil
       if album.photos[album.cover]!=nil
         @photos[@i]=album.photos[album.cover]
       else
         @photos[@i]=album.photos[0]
       end
     else 
        if album.photos[0]!=nil
          @photos[@i]=album.photos[0]
        end
     end

     @i+=1
    end
    @i=0
    render :action=>"album_list"
   end

  def new_photo
    @album=Album.find(params[:id])
    @photo = Photo.new(params[:photo])
    begin
      if request.post?
        if params[:file]==''
          flash[:notice] = _('Please specify a file')
        end
        if @photo.valid? and params[:file]!=''
          @photo.user_id = session[:user]
          @album.photos<<@photo
          @photo.save
          st=params[:tags]

           tagnames=st.split(/\s*,\s*/)
             for tagname in tagnames
              @photo.add_tag(tagname)
             end

       @path = File.basename(params[:file].original_filename,".*")

          name=params[:name]          
         
         if name!=''
           @photo.title = name
         else 
           @photo.title = @path
         end
         @photo.save
         file = params[:file].path
         @photo.write(file, @album.title, 1)
         @album.save
         flash[:notice] = _('Photo was successfully created.')
         redirect_to :action => 'album_page',:id=>@album
        else
          flash[:notice] = _('Please specify a file') if params[:file].nil?
        end
      end
    end
    rescue RuntimeError
    flash[:notice] = _('Unknown extension. Download File with suitable extension.')
    @photo.destroy
    rescue Magick::ImageMagickError
    flash[:notice] = _('Unknown extension. Download File with suitable extension.')
    @photo.destroy
    rescue RuntimeError
    flash[:notice] = _('Unknown extension. Download File with suitable extension.')
    @photo.destroy

  end
  


  def synchronize
    @albums = Album.find :all
    for alb in @albums 
      if (not File.exist?(RAILS_ROOT + '/public/photos/' + alb.title + "/"))
        @i=0
        @photos = alb.photos 
        while @i<@photos.size
          @photos[@i].rm(alb.title)
          @i=@i+1
        end
        alb.destroy
      end
    end
    
    
    for alb in @albums 
      @photos = alb.photos
      for ph in @photos
        if (not File.exist?(RAILS_ROOT + '/public/photos/' + alb.title + "/" + "#{ph.id}.jpg"))
          ph.rm('')
          ph.destroy
        end
      end
    end
    
    @files = Array.new
    @files = Dir.entries(RAILS_ROOT + '/public/photos')
    
    @i=2
    @k=0
    if (@files[@i]=='.svn')
      @i+=1
    end
    while @i<@files.size
      for alb in @albums 
        if (@files[@i] == alb.title)
          @k=1
          break
        end
      end
     
      if (@k == 0)
        @albm = Album.new
        @albm.title = @files[@i]
        @albm.save
      end
      @k=0
      @i=@i+1
    end
    
    @files.clear
    @albums = Album.find :all
    for alb in @albums
      @files = Dir.entries(RAILS_ROOT + '/public/photos/' + alb.title)
      @i=2
      @k=0
      @photos = alb.photos 
      while @i<@files.size
        name = File.basename(RAILS_ROOT + '/public/photos/' + alb.title+ '/' +@files[@i], ".jpg") 
        for ph in @photos 
          if (name == String(ph.id))
            @k=1
            break
          end
        end
   
        if (@k == 0)
          @photo = Photo.new
          @photo.title = name
          @photo.user_id = session[:user]
          alb.photos<<@photo
          @photo.save
          file = RAILS_ROOT + '/public/photos/' + alb.title+ '/' +@files[@i]
          @photo.write(file, alb.title, 0)
          File.rename(RAILS_ROOT + '/public/photos/' + alb.title+ '/' +@files[@i], RAILS_ROOT + '/public/photos/' + alb.title+ '/' + "#{@photo.id}" +".jpg")
        end
        @k=0
        @i=@i+1
      end
    end
    redirect_to  :action=>"album_list"
  end
  
  def update
    @photo=Photo.find(params[:id])
    @album=@photo.albums[0]
    if request.post? and @photo.update_attributes(params[:photo]) and @photo.save
      flash[:notice] = "\"#{@photo.title}\"" + _("has been saved.")
      redirect_to :controller=>"admin", :action=>"album_page", :id => @album
    else
      render :action=>"edit_photo", :id=>@photo
    end
  end

  def gallery_settings
    @gallery=Settings.get_gallery_name
    params[:gallery_name]=@gallery.value
    params[:need_login]=(Settings.get_need_login)
    params[:lang]= I18nService.instance.lang
    params[:name] = current_user.first
    params[:surname] = current_user.last
    params[:log] = current_user.login
    params[:email] = current_user.email
    params[:schemes_list] = SchemeManager.get_list_of_schemes
    params[:current_scheme] = Settings.get_scheme
    params[:cloud_range] = Settings.get_cloud_range
  end
  
  def apply_settings
    if request.post? 
      check = 1
           
      st=params[:password]
      while st do
      password,st=st.split(/\s*,\s*/)
    end
    
      if password
        if params[:password]==params[:password_confirmation]
          current_user.crypted_password = current_user.encrypt(params[:password])
          current_user.save
          else 
            check = 0
            flash[:notice] = _("Two passwords dismatch")
            redirect_to :controller=>"admin", :action=>"gallery_settings"
        end
      end
      if check==1
      current_user.sav( params[:log],params[:name],params[:surname],params[:email])
      
      if ['ru', 'en'].include?(params[:lang])
        ri18n_init(params[:lang])
      end
      #neccesary code #
      flash[:notice]="blblblb"
      #               #
      if params[:gallery_name]!=''
        Settings.set_gallery_name(params[:gallery_name])
      else
      flash[:notice] = _("Gallery_name can't be empty.")
      end
      Settings.set_need_login(params[:need_login])
      Settings.set_scheme(params[:scheme])
      Settings.set_cloud_range(params[:cloud_range])

      if !flash[:notice].include? "Gallery_name can't be empty."
        flash[:notice] = _("New settings has been saved.")
      end
      redirect_to :controller=>"admin", :action=>"gallery_settings"
      end
    else
      render :action=>"gallery_settings"
    end
  end


# ========I18n section=====================================

# Language settings

  def language
    if ['ru', 'en'].include?(params[:language])
      ri18n_init(params[:language])
    end
    @title = _('language')
    redirect_to :back
  end

  def ri18n_init(language = nil)
     I18nService.instance.lang = language || LANGUAGE     
  end

#  def language
#  	@lang = 'ru'
#  	I18nService.instance.lang = @lang 
#  	redirect_to :action => 'index'
#  end

#=========Coded by "I18n" developer's group================

end